Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Datatypes

Python List

Lists in Python

In Python, lists are an incredibly useful way to store and manage collections of data. Let's break down their key characteristics and how you can work with them.

Core Features

Ordered: Lists maintain the order in which you insert items. This means that the position of each element has significance. ✦ Mutable: You can change the contents of a list after you create it. This includes adding, removing, or modifying existing items. ✦ Heterogeneous: A list can hold elements of different data types. You could have numbers, strings, and even other lists all within a single list. You have two primary ways to create lists in Python:

Square brackets:

python list declaration example using Square brackets my_list = [10, "hello", True, 3.14] print(my_list)

Output

[10, "hello", True, 3.14]

list() constructor:

python list declaration example using list constructor my_list = list((5, "world", False)) print(my_list)

Output

[5, "world", False]

Built-in methods in Lists

append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the first item with the specified value reverse() Reverses the order of the list sort() Sorts the list

More points about Lists

Storing sequences: Represent sequences of related items, such as a list of student names or product prices. ✦ Implementing stacks and queues: The way you add and remove elements from lists aligns well with these fundamental data structures. ✦ Iterating over elements: Use for loops to process each element in a list sequentially. Example
Basic example of list datatype in python with methods shopping_list = ["eggs", "bread", "milk"] print(shopping_list[0]) shopping_list.append("butter") print(shopping_list) shopping_list.remove("bread") print(shopping_list)

Output

eggs ["eggs", "bread", "milk", "butter"] ["eggs", "milk", "butter"]

  📌TAGS

★python ★ datatypes ★ List ★ append

Tutorials